import 'package:m_todo/domain/entity/account_entity.dart';
import 'package:m_todo/domain/service/account_service.dart';

/// 账户服务用例
class AccountUseCase {
  final AccountService accountService;

  AccountUseCase(this.accountService);

  /// 登陆
  Future<LoginState> login(String name, String password) async {
    try {
      if (await accountService.isLogin()) {
        return LoginState.repeatLogin;
      }

      var account = await accountService.getAccountByName(name);
      if (account == null || account.name == null) {
        return LoginState.invalidUserName;
      }

      if (account.password != password) {
        return LoginState.invalidPassword;
      }

      /// 保存登陆状态
      await accountService.saveLoginState(account);
    } catch (e) {
      return LoginState.sysErr;
    }
    return LoginState.success;
  }

  /// 登出
  Future<void> logout() {
    return accountService.clearLoginState();
  }

  /// 获取当前登陆账号
  Future<AccountEntity?> getLoginAccount() {
    return accountService.getLoginAccount();
  }
}

enum LoginState {
  /// 登陆成功
  success,

  /// 无效用户名
  invalidUserName,

  /// 密码不正确
  invalidPassword,

  /// 重复登陆
  repeatLogin,

  /// 系统异常
  sysErr
}
